"""
管理后台-组织机构相关的请求响应模型
"""
from datetime import datetime
from typing import List, Optional

from pydantic import BaseModel, ConfigDict, Field

from app.core.constants import BoolEnum, OrgTypeEnum
from app.schemas.common import PaginationResult


class AdminOrganizationBase(BaseModel):
    """管理后台-组织机构基础模型"""
    name: str = Field(
        ..., 
        min_length=2, 
        max_length=255, 
        description="机构名称",
        pattern="^[a-zA-Z0-9\u4e00-\u9fa5][a-zA-Z0-9\u4e00-\u9fa5-_]*$"  # 只允许中文、字母、数字、横杠、下划线
    )
    parent_id: Optional[int] = Field(None, description="父级ID", gt=0)  # 父级ID必须大于0
    sort: int = Field(0, description="排序", ge=0)  # 排序值必须大于等于0
    org_type: OrgTypeEnum = Field(..., description="组织类型")
    is_show: BoolEnum = Field(BoolEnum.TRUE, description="是否显示")

    model_config = ConfigDict(
        str_strip_whitespace=True,  # 自动去除字符串首尾空格
        str_min_length=2,
        str_max_length=255
    )


class AdminOrganizationCreateRequest(AdminOrganizationBase):
    """管理后台-组织机构创建请求"""
    pass


class AdminOrganizationUpdateRequest(BaseModel):
    """管理后台-组织机构更新请求"""
    name: Optional[str] = Field(
        None,
        min_length=2,
        max_length=255,
        pattern="^[a-zA-Z0-9\u4e00-\u9fa5][a-zA-Z0-9\u4e00-\u9fa5-_]*$"
    )
    parent_id: Optional[int] = Field(None, gt=0)
    sort: Optional[int] = Field(None, ge=0)
    org_type: Optional[OrgTypeEnum] = None
    is_show: Optional[BoolEnum] = None


class AdminOrganizationResponse(AdminOrganizationBase):
    """管理后台-组织机构响应"""
    id: int = Field(..., description="组织ID")
    created_at: datetime = Field(..., description="创建时间")
    children: List["AdminOrganizationResponse"] = Field(default_factory=list, description="子组织")

    model_config = ConfigDict(from_attributes=True)


class AdminOrganizationTreeNode(BaseModel):
    """管理后台-组织机构树节点"""
    id: int = Field(..., description="组织ID")
    name: str = Field(..., description="机构名称")
    parent_id: Optional[int] = Field(None, description="父级ID")
    sort: int = Field(..., description="排序")
    org_type: OrgTypeEnum = Field(..., description="��织类型")
    is_show: BoolEnum = Field(..., description="是否显示")
    children: List["AdminOrganizationTreeNode"] = Field(default_factory=list, description="子节点")

    model_config = ConfigDict(from_attributes=True)


class AdminOrganizationListFilters(BaseModel):
    """管理后台-组织机构列表过滤条件"""
    name: Optional[str] = Field(None, description="机构名称(模糊匹配)")
    parent_id: Optional[int] = Field(None, description="父级ID")
    org_type: Optional[OrgTypeEnum] = Field(None, description="组织类型")
    is_show: Optional[BoolEnum] = Field(None, description="是否显示")


# 定义响应类型
AdminOrganizationTreeResponse = List[AdminOrganizationTreeNode]
AdminOrganizationListResponse = PaginationResult[AdminOrganizationResponse] 